<?php
/*
 * @Description    : WebSocketAuthMiddleware
 * @Author         : QianLong
 * @Date           : 2023-05-04 10:39:14
 * @LastEditors    : QianLong
 * @Site           : http://www.21ds.cn
 * @LastEditTime   : 2023-11-14 11:21:43
 */

declare(strict_types=1);

namespace App\Middleware;

use App\Common\RedisCache;
use Hyperf\WebSocketServer\Context;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class WebSocketAuthMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    private $response;

    public function __construct(ContainerInterface $container, \Hyperf\HttpServer\Contract\ResponseInterface $response)
    {
        $this->container = $container;
        $this->response = $response;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        //通过 isAuth 方法拦截握手请求并实现权限检查
        if (!$this->isAuth($request)) {
            return $this->response->raw('Forbidden');
        }
        return $handler->handle($request);
    }

    protected function isAuth($request)
    {
        // return true;
        $params = $request->getQueryParams();
        try {
            $socketServer = (new RedisCache)->getWsServer($params['ws_id']);
            if (empty($socketServer)) {
                return false;
            }
            if ($socketServer['status'] != 1) {
                return false;
            }
            $nws_sign = hash('sha256', $params['ws_id'] .
            md5($socketServer['server_secret']));
            if ($nws_sign != $params['ws_sign']) {
                return false;
            }
            Context::set('socketServer', $socketServer);
            return true;
        } catch (\Exception $e) {
            return false;
        }
        return true;
    }
}
